<template>
    <div class="pager" v-if="total > 0">
        <a href="" class="pager-item" :class="{ disabled: page === 1 }" @click.prevent="handleChange(1)">首页</a>
        <a href="" class="pager-item" :class="{ disabled: page === 1 }" @click.prevent="handleChange(page - 1)">上一页</a>
        <a href="" class="pager-item" 
            v-for="num in numbers" :key="num" v-text="num" 
            @click.prevent="handleChange(num)" :class="{ active: num === page }">
        </a>
        <a href="" class="pager-item" :class="{ disabled: page === pageNumber }" @click.prevent="handleChange(page + 1)">下一页</a>
        <a href="" class="pager-item" :class="{ disabled: page === pageNumber }" @click.prevent="handleChange(pageNumber)">尾页</a>
        <span class="pager-text">第<i v-text="page"></i>页 共<i v-text="pageNumber"></i>页</span>
    </div>
</template>

<script>
export default {
    props: {
        page: { //当前页码
            type: Number,
            default: 1
        },
        total: { //总数据量
            type: Number,
            default: 0
        },
        limit: { //每页显示多少条数据
            type: Number,
            default: 10
        },
        panelNumber: { //默认显示多少个数字页
            type: Number,
            default: 10
        }
    },
    computed: {
        pageNumber() {  //总页数
            return Math.ceil(this.total / this.limit);
        },
        minNumber() {
            let n = this.page - this.panelNumber / 2;
            if (n < 1) {
                n = 1;
            } else if (n + this.panelNumber > this.pageNumber) {
                n = this.pageNumber - this.panelNumber + 1;
            }
            return n;
        },
        maxNumber() {
            let n = this.minNumber + this.panelNumber - 1;
            if (n > this.pageNumber) {
                n = this.pageNumber;
            }
            return n;
        },
        numbers() { //页码数组
            let nums = [];
            for (let i = this.minNumber; i <= this.maxNumber; i++) {
                nums.push(i);
            }
            return nums;
        },
    },
    methods: {
        handleChange(newPage) {
            // 判断页面是否变化
            if (newPage === this.page) {
                return;
            } else if (newPage < 1) {
                newPage = 1;
            } else if (newPage > this.pageNumber) {
                newPage = this.pageNumber
            }
            this.$emit('pageChange', newPage);
        }
    }
}
</script>

<style scoped>
.pager {
    text-align: center;
    margin: 20px 0;
}
.pager a {
    text-decoration: none;
}
.pager .pager-item {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #ccc;
    margin: 8px;
    cursor: pointer;
    color: rgb(96, 96, 224);
}
.pager .pager-item.disabled {
    color: #ccc;
    cursor: not-allowed;
}
.pager .pager-item.active {
    color: #f40;
    border-color: #f40;
    cursor: auto;
}
.pager-text i {
    font-style: normal;
}
</style>